<?php
/**
 * API
 *
 */

require($_SERVER['DOCUMENT_ROOT'] . '/../api.inc.php');

$result = array();
$current_user_id = '';
$ec = 0;
$rest_api_ec = 0;

try {
    $api_request = new ApiRequest();
    $format = $api_request->GetApiEchoFormat();
    $invoke_controller = $api_request->GetApiController();
    $invoke_method = $api_request->GetApiMethod();
	if ($api_request->verify() === ApiErr::API_EC_SUCCESS) {
		//$current_user_id = $api_request->GetCurrentUserId();
	}
	if (class_exists($invoke_controller) && method_exists($module=new $invoke_controller($current_user_id), $invoke_method))
	{
		$result = $module->$invoke_method();
	}else{
		throw new Exception(ApiErr::API_EC_UNKNOWN_METHOD);
	}

} catch (Exception $e) {
	$ec = $e->getMessage();
	$rest_api_ec = $e->getCode();//eg: sapi

	header("HTTP/1.0 400 Bad Request");

	if (is_numeric($ec)) {
		$error_msg = ApiErr::GetErrorDescriptor($ec);
		$result = array(
			'request'		=> ApiUtility::GetBaseUri(),
			'error_code' 	=> $ec, 
			'error_msg' 	=> $rest_api_ec == 0 ? $error_msg : "$error_msg ($rest_api_ec)",
		);
	} else {
		$result = array(
			'request'		=> ApiUtility::GetBaseUri(),
			'error_code' 	=> ApiErr::API_EC_SYSERROR, 
			'error_msg' 	=> ApiErr::GetErrorDescriptor(ApiErr::API_EC_SYSERROR),
		);
	}
}

switch ($format) {
	case 'json':
	default:
		header('Content-type: application/json');
		echo ApiEcho::RenderJson($result);
		break;
}
